package cn._2dland.sakushi.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.sakushi.SakushiInfo;
import cn._2dland.sakushi.client.Mention;
import cn._2dland.sakushi.client.XinaClient;
import cn._2dland.sakushi.jdo.LastQuestion;
import cn._2dland.sakushi.jdo.PMFactory;
import cn._2dland.sakushi.jdo.Question;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

/**
 * 助理Servlet
 * 负责定期获取未处理的消息
 * @author deadblue
 */
public class XinaAgentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		try {
			// 最后一条消息的ID记录
			LastQuestion lq = null;
			try{ lq = pm.getObjectById(LastQuestion.class, new Long(2)); }
			catch(Exception e){ lq = null; }

			String lastId = lq==null ? null : lq.getStatusId();

			// 获取所有未处理的消息，存储并为其建立处理队列
			XinaClient xc = new XinaClient(SakushiInfo.XINA_USERNAME, SakushiInfo.XINA_PASSWORD, SakushiInfo.XINA_APPKEY);
			List<Mention> mentions = xc.getMentions(lastId);

			// 获取处理队列
			Queue queue = QueueFactory.getQueue("sakushi-queue");

			for(int i=mentions.size()-1; i>=0; i--) {
				Mention mention = mentions.get(i);
				// 读取消息信息
				String statusId = mention.getStatusId();
				String sourceId = mention.getSourceId();
				String text = mention.getText();
				// 读取发送者信息
				String userId = mention.getUserId();
				String userName = mention.getUserName();

				try {
					// 将消息持久化存储
					Question q = new Question(statusId, userId, userName, text);
					q.setSourceId(sourceId);
					pm.makePersistent(q);

					// 创建处理任务，放入队列
					TaskOptions task = TaskOptions.Builder.withUrl("/xinaSakushi");
					task.method(TaskOptions.Method.POST);
					task.param("status_id", statusId);
					queue.add(task);

					// 表示最后处理的消息
					lastId = statusId;
				}
				catch (Exception e) { e.printStackTrace(); }
			}

			// 记录最后一次处理的消息
			if(lastId != null) {
				if(lq == null) {
					lq = new LastQuestion(new Long(2), lastId);
					pm.makePersistent(lq);
				}
				else {
					lq.setStatusId(lastId);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			pm.close();
		}
	}
}
